import { validate, ValidatorOptions } from "class-validator";
import errors from "restify-errors";
import { Repository, SaveOptions } from "typeorm";

export abstract class ValidateRepository<T extends object> extends Repository<T> {
  async saveEntity(
    entity: T,
    options?: SaveOptions,
    validatorOptions?: ValidatorOptions
  ): Promise<T> {
    const errs = await validate(entity, validatorOptions);
    if (errs.length > 0) {
      throw new errors.InvalidArgumentError(errs[0].property);
    }

    return super.save(entity, options);
  }

  async saveEntityList(
    entities: T[],
    options?: SaveOptions,
    validatorOptions?: ValidatorOptions
  ): Promise<T[]> {
    for (const entity of entities) {
      const errs = await validate(entity, validatorOptions);
      if (errs.length > 0) {
        throw new errors.InvalidArgumentError(errs[0].property);
      }
    }

    return super.save(entities, options);
  }
}
